package com.lin.subject.domain.service.impl;

import com.lin.subject.commom.entity.PageResult;
import com.lin.subject.commom.enums.IsDeletedFlagEnum;
import com.lin.subject.commom.util.IdWorkerUtil;
import com.lin.subject.commom.util.LoginUtil;
import com.lin.subject.domain.convert.SubjectInfoConvert;
import com.lin.subject.domain.entity.SubjectInfoBO;
import com.lin.subject.domain.entity.SubjectOptionBO;
import com.lin.subject.domain.handler.subject.SubjectTypeHandler;
import com.lin.subject.domain.handler.subject.SubjectTypeHandlerFactory;
import com.lin.subject.domain.redis.RedisUtil;
import com.lin.subject.domain.service.SubjectInfoDomainService;
import com.lin.subject.domain.service.SubjectLikedDomainService;
import com.lin.subject.infra.basic.entity.SubjectInfo;
import com.lin.subject.infra.basic.entity.SubjectInfoEs;
import com.lin.subject.infra.basic.entity.SubjectLabel;
import com.lin.subject.infra.basic.entity.SubjectMapping;
import com.lin.subject.infra.basic.service.*;
import com.lin.subject.infra.entity.UserInfo;
import com.lin.subject.infra.rpc.UserRpc;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SubjectInfoDomainServiceImpl implements SubjectInfoDomainService {

    @Resource
    private SubjectInfoService subjectInfoService;

    @Resource
    private SubjectMappingService subjectMappingService;

    @Resource
    private SubjectTypeHandlerFactory subjectTypeHandlerFactory;

    @Resource
    private SubjectLabelService subjectLabelService;

    @Resource
    private SubjectEsService subjectEsService;

    @Resource
    private SubjectLikedDomainService subjectLikedDomainService;

    @Resource
    private UserRpc userRpc;

    @Resource
    private RedisUtil redisUtil;

    private static final String RANK_KEY = "subject_rank";



    /**
     * 新增题目
     * 1、插入题目基本信息
     * 2、插入label信息及分类信息 ---> 多对多 插入SubjectMapping 映射表
     * 3、插入每道题的信息 ---> 工厂 + 策略
     *
     * @param subjectInfoBo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SubjectInfoBO subjectInfoBo) throws Exception {

        SubjectInfo subjectInfo = SubjectInfoConvert.INSTANCE.subjectBoToSubjectInfo(subjectInfoBo);
        subjectInfo.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        subjectInfoService.insert(subjectInfo);

        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfoBo.getSubjectType());
        subjectInfoBo.setId(subjectInfo.getId());
        handler.insertSubject(subjectInfoBo);

        LinkedList<SubjectMapping> subjectMappings = new LinkedList<>();

        // 插入映射表
        subjectInfoBo.getCategoryIds().forEach(categoryId ->
                subjectInfoBo.getLabelIds().forEach(labelId -> {
                    SubjectMapping subjectMapping = new SubjectMapping();
                    subjectMapping.setCategoryId(categoryId);
                    subjectMapping.setLabelId(labelId);
                    subjectMapping.setSubjectId(subjectInfo.getId());
                    subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
                    subjectMappings.add(subjectMapping);
                })
        );

        // 批量插入
        subjectMappingService.batchInsert(subjectMappings);

        // 同步es
        SubjectInfoEs subjectInfoEs = subjectInfo2ES(subjectInfoBo);
        subjectEsService.insert(subjectInfoEs);


        //redis放入zadd计入排行榜
//        redisUtil.addScore(RANK_KEY, LoginUtil.getLoginId(), 1);
    }



    /**
     * 题目分页查询
     *
     * @param subjectInfoBO
     * @return
     */
    @Override
    public PageResult<SubjectInfoBO> getSubjectPage(SubjectInfoBO subjectInfoBO) {
        PageResult<SubjectInfoBO> pageResult = new PageResult<>();
        pageResult.setPageNo(subjectInfoBO.getPageNo());
        pageResult.setPageSize(subjectInfoBO.getPageSize());
        int start = (subjectInfoBO.getPageNo() - 1) * subjectInfoBO.getPageSize();
        SubjectInfo subjectInfo = SubjectInfoConvert.INSTANCE.convertBoToInfo(subjectInfoBO);
        int count = subjectInfoService.countByCondition2(subjectInfo,
                subjectInfoBO.getCategoryId());
        if (count == 0) {
            return pageResult;
        }
        List<SubjectInfo> subjectInfoList = subjectInfoService.queryPage2(subjectInfo, subjectInfoBO.getCategoryId(), start, subjectInfoBO.getPageSize());
        List<SubjectInfoBO> subjectInfoBOS = SubjectInfoConvert.INSTANCE.convertListInfoToBO(subjectInfoList);
        subjectInfoBOS.forEach(info->{
            SubjectMapping subjectMapping = new SubjectMapping();
            subjectMapping.setSubjectId(info.getId());
            List<SubjectMapping> mappingList = subjectMappingService.queryCondition(subjectMapping);
            List<Long> labelIds = mappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
            List<SubjectLabel> labelList = subjectLabelService.batchQueryById(labelIds);
            List<String> labelNames = labelList.stream().map(SubjectLabel::getLabelName).collect(Collectors.toList());
            info.setLabelName(labelNames);
        });
        pageResult.setRecords(subjectInfoBOS);
        pageResult.setTotal(count);
        return pageResult;
    }

    /**
     * 查询题目详情
     *
     * @param subjectInfoBO
     * @return
     */
    @Override
    public SubjectInfoBO querySubjectInfo(SubjectInfoBO subjectInfoBO) {
        SubjectInfo subjectInfo = subjectInfoService.queryById(subjectInfoBO.getId());
        if(Objects.isNull(subjectInfo)){
            throw new RuntimeException("题目不存在");
        }
        Integer subjectType = subjectInfo.getSubjectType();
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectType);
        SubjectOptionBO subjectOptionBO = handler.query(subjectInfo.getId());
        SubjectInfoBO bo = SubjectInfoConvert.INSTANCE.convertOptionAndInfo(subjectOptionBO,subjectInfo);

        List<SubjectMapping> mappingList = subjectMappingService.getBySubjectId(subjectInfoBO.getId());
        if(!mappingList.isEmpty()){
            List<Long> labelIds = mappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
            List<SubjectLabel> subjectLabelList = subjectLabelService.batchQueryById(labelIds);
            if(!subjectLabelList.isEmpty()){
                List<String> labelNames = subjectLabelList.stream().map(SubjectLabel::getLabelName).collect(Collectors.toList());
                bo.setLabelName(labelNames);
            }
        }

        // 获取是否点赞
        bo.setLiked(subjectLikedDomainService.getLiked(subjectInfoBO.getId(),LoginUtil.getLoginId()));
        // 获取点赞数量
        bo.setLikedCount(subjectLikedDomainService.getLikedCount(subjectInfoBO.getId()));

        assembleSubjectCursor(subjectInfoBO, bo);
        return bo;
    }

    private void assembleSubjectCursor(SubjectInfoBO subjectInfoBO, SubjectInfoBO bo) {
        Long categoryId = subjectInfoBO.getCategoryId();
        Long labelId = subjectInfoBO.getLabelId();
        Long subjectId = subjectInfoBO.getId();
        if (Objects.isNull(categoryId) || Objects.isNull(labelId)) {
            return;
        }
        Long nextSubjectId = subjectInfoService.querySubjectIdCursor(subjectId, categoryId, labelId, 1);
        bo.setNextSubjectId(nextSubjectId);
        Long lastSubjectId = subjectInfoService.querySubjectIdCursor(subjectId, categoryId, labelId, 0);
        bo.setLastSubjectId(lastSubjectId);
    }

    /**
     * 删除题目
     *
     * @param id
     */
    @Override
    public void deleteSubject(Long id) {
        SubjectInfo subjectInfo = subjectInfoService.queryById(id);
        if(Objects.isNull(subjectInfo)){
            throw new RuntimeException("题目不存在");
        }
        Integer subjectType = subjectInfo.getSubjectType();
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectType);
        handler.deleteSubject(id);

        // 删除映射关系
        subjectMappingService.removeMapping(id);
        // 删除题目
        subjectInfoService.removeSubject(id);
    }

    /**
     * 分页、全文检索
     *
     * @param subjectInfoBO
     * @return
     */
    @Override
    public PageResult<SubjectInfoEs> getSubjectPageBySearch(SubjectInfoBO subjectInfoBO) {
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        subjectInfoEs.setKeyWord(subjectInfoBO.getKeyWord());
        PageResult<SubjectInfoEs> subjectInfoEsPageResult = subjectEsService.querySubjectList(subjectInfoEs);
        return subjectInfoEsPageResult;
    }

    /**
     * 获取贡献榜
     *
     * @return
     */
    @Override
    public List<SubjectInfoBO> getContributeList() {
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisUtil.rankWithScore(RANK_KEY, 0, 5);
        if (CollectionUtils.isEmpty(typedTuples)) {
            return Collections.emptyList();
        }

        List<SubjectInfoBO> boList = new LinkedList<>();
        typedTuples.forEach((subjectInfo -> {
            SubjectInfoBO subjectInfoBO = new SubjectInfoBO();
            subjectInfoBO.setSubjectCount(subjectInfo.getScore().intValue());
            UserInfo userInfo = userRpc.getUserInfo(subjectInfo.getValue());
            subjectInfoBO.setCreateUser(userInfo.getNickName());
            subjectInfoBO.setCreateUserAvatar(userInfo.getAvatar());
            boList.add(subjectInfoBO);
        }));
        return boList;
    }

    /***************私有方法***************/

    /**
     * subjectInfo转换es
     * @param subjectInfo
     * @return
     */
    private SubjectInfoEs subjectInfo2ES(SubjectInfoBO subjectInfo) {
        SubjectInfoEs subjectInfoEs = new SubjectInfoEs();
        subjectInfoEs.setDocId(new IdWorkerUtil(1,1,1).nextId());
        subjectInfoEs.setSubjectId(subjectInfo.getId());
        subjectInfoEs.setSubjectAnswer(subjectInfo.getSubjectAnswer());
        subjectInfoEs.setCreateTime(new Date().getTime());
        subjectInfoEs.setCreateUser("鸡翅");
        subjectInfoEs.setSubjectName(subjectInfo.getSubjectName());
        subjectInfoEs.setSubjectType(subjectInfo.getSubjectType());

        return subjectInfoEs;
    }
}
